<?php


namespace App\Http\Controllers\Saas;


use App\Contract\Platform;
use App\Http\Controllers\Controller;
use App\Model\Staff;
use App\Utils\Result;
use App\Utils\Token;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class LoginController extends Controller
{
    public function login(Request $request): \Illuminate\Http\JsonResponse
    {
        $username = $request->input('mobile');
        $password = $request->input('password');
        if (!$username OR !$password) {
            return Result::error(400, '登录失败，账号或密码错误');
        }
        $staff = Staff::where('mobile', $username)->first();
        if (!$staff) {
            return Result::error(400, '登录失败，账号或密码错误');
        }
        if (!password_verify($password, $staff->password)) {
            return Result::error(400, '登录失败，账号或密码错误');
        }
        if (!$staff->token) {
            $staff->token = Str::random(32);
            $staff->save();
        }
        return Result::success([
            'token' => $staff->token,
            'name' => $staff->name,
            'mobile' => $staff->mobile,
            'roles'=>$staff->roles
        ]);
    }

    public function authInfo(): \Illuminate\Http\JsonResponse
    {
        $staff = Token::getUser();
//        $role = $staff->role()->first();
        return Result::success([
            'name' => $staff->name,
            'mobile' => $staff->mobile,
            'roles' => $staff->roles
        ]);
    }

    public function changePassword(Request $request): \Illuminate\Http\JsonResponse
    {
        $newPassword = $request->input('newPassword');
        $oldPassword = $request->input('oldPassword');
        $staff = Token::getUser();
        if (!$newPassword OR !$oldPassword) {
            return Result::error(400, '缺少字段');
        }
        if (!password_verify($oldPassword, $staff->password) && env('APP_ENV') == 'production') {
            return Result::error(400, '原密码错误');
        }
        $staff->password = Hash::make($newPassword);
        $staff->save();
        return Result::success();
    }
}
